package com.dbsync.task;

import com.dbsync.core.DBUtil;
import com.dbsync.core.SQLExecutor;
import com.dbsync.exception.DbsyncUncaughtExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

/**
 * 数据库同步任务启动类
 */
public class TaskExcutor {
    // 日志
    private final static Logger logger = LoggerFactory.getLogger(TaskExcutor.class);


    /**
     * 启动同步任务
     */
    public static void start(){
        logger.info("*************************************数据库同步程序已启动*************************************\n");
        DBUtil dbUtil = new DBUtil();
        try {
            dbUtil.init();
            Thread.setDefaultUncaughtExceptionHandler(new DbsyncUncaughtExceptionHandler());
            int count = dbUtil.getTargets().size();
            for (int index=0;index<count;index++){
                Date date = dbUtil.getTargets().get(index).getTime();
                long period = dbUtil.getTargets().get(index).getPeriod();
                 if (date != null){
                     if (date.before(new Date())) {
                         date = addDay(date, 1);
                     }
                     if (period == 0){
                         // 启动定时任务
                         new Timer().schedule(new Task(new SQLExecutor(dbUtil, index), logger), date);
                     }else{
                         // 启动定时任务
                         new Timer().schedule(new Task(new SQLExecutor(dbUtil, index), logger), date, period);
                     }
                 }else{
                     if (period == 0){
                         // 启动定时任务
                         new Timer().schedule(new Task(new SQLExecutor(dbUtil, index), logger), 1000);
                     }else{
                         // 启动定时任务
                         new Timer().schedule(new Task(new SQLExecutor(dbUtil, index), logger), 1000, period);
                     }
                 }
            }
            Runtime runtime = Runtime.getRuntime();
            runtime.addShutdownHook(new Thread(){
                @Override
                public void run() {
                    logger.info("*************************************数据库同步程序已终止*************************************");
                }
            });
        }catch (Exception e){
            logger.error(e.getMessage());
            logger.info("*************************************数据库同步程序已终止*************************************");
        }
    }

    /**
     * 增加天数
     * @param date 日期对象
     * @param num 加减天数
     * @return 返回date对象
     */
    private static Date addDay(Date date, int num) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, num);
        return startDT.getTime();
    }
}
